// 图片功能相关JavaScript代码
layui.use(['layer', 'jquery'], function() {
    var layer = layui.layer;
    var $ = layui.jquery;
    
    // 当前选中的账单ID
    var currentAid = '';
    // 待上传的图片队列
    window.pendingImages = [];
    
    /**
     * 显示图片详情弹窗
     */
    window.showImageDetailModal = function(aid, accountItem) {
        currentAid = aid;
        // 加载并显示该账单的所有图片
        loadAccountImages(aid);
        
        layer.open({
            type: 1,
            title: '图片详情 - ' + (accountItem ? accountItem.description : '未知账单'),
            content: $('#imageDetailModal'),
            area: ['700px', '600px'],
            success: function() {
                // 绑定添加图片按钮事件
                $('#addImageBtn').off('click').on('click', function() {
                    showUploadImageModal();
                });
            },
            end: function() {
                currentAid = '';
            }
        });
    };
    
    // 上传弹窗索引
    var uploadModalIndex = null;
    // 更新弹窗索引
    var updateModalIndex = null;
    
    /**
     * 显示图片上传弹窗
     */
    function showUploadImageModal() {
        // 清空表单
        $('#imageFile').val('');
        $('#imageDescription').val('');
        $('#uploadAid').val(currentAid);
        
        uploadModalIndex = layer.open({
            type: 1,
            title: '上传图片',
            content: $('#uploadImageModal'),
            area: ['500px', '300px'],
            success: function() {
                // 绑定上传和取消按钮事件
                $('#confirmUploadBtn').off('click').on('click', function() {
                    uploadImage();
                });
                
                $('#cancelUploadBtn').off('click').on('click', function() {
                    if (uploadModalIndex) {
                        layer.close(uploadModalIndex);
                        uploadModalIndex = null;
                    }
                });
            },
            end: function() {
                uploadModalIndex = null;
            }
        });
    }
    
    /**
     * 显示图片更新弹窗
     */
    function showUpdateImageModal(iid, currentDescription) {
        $('#updateIid').val(iid);
        $('#updateImageDescription').val(currentDescription);
        
        updateModalIndex = layer.open({
            type: 1,
            title: '更新图片描述',
            content: $('#updateImageModal'),
            area: ['500px', '250px'],
            success: function() {
                // 绑定确认和取消按钮事件
                $('#confirmUpdateBtn').off('click').on('click', function() {
                    updateImageDescription();
                });
                
                $('#cancelUpdateBtn').off('click').on('click', function() {
                    if (updateModalIndex) {
                        layer.close(updateModalIndex);
                        updateModalIndex = null;
                    }
                });
            },
            end: function() {
                updateModalIndex = null;
            }
        });
    }
    
    /**
 * 加载账单的所有图片
 */
function loadAccountImages(aid) {
    // 从全局window.user_info对象中获取当前用户的ID
    var currentUserId = window.user_info && window.user_info.uid ? window.user_info.uid : 'e0873ff1-ba5f-496c-95a7-40c8c8e7faca';
    
    axios.get('/api/image/list/', {
        params: {
            uid: currentUserId,
            aid: aid
        }
    })
    .then(function(res) {
        if (res.data.code === 0 && res.data.data) {
            renderImageList(res.data.data);
        } else {
            layer.msg('获取图片失败：' + (res.data.message || '未知错误'), {icon: 2});
            // 使用mock数据作为备选
            renderMockImageList();
        }
    })
    .catch(function() {
        layer.msg('网络错误，显示示例图片', {icon: 0});
        // 使用mock数据
        renderMockImageList();
    });
}

/**
 * 渲染mock图片数据（当API不可用时）
 */
function renderMockImageList() {
    var mockImages = [
        {
            iid: 'mock-1',
            image_url: 'https://picsum.photos/id/237/400/300',
            description: '示例图片 1'
        },
        {
            iid: 'mock-2',
            image_url: 'https://picsum.photos/id/238/400/300',
            description: '示例图片 2'
        },
        {
            iid: 'mock-3',
            image_url: 'https://picsum.photos/id/239/400/300',
            description: '示例图片 3'
        }
    ];
    
    renderImageList(mockImages);
}
    
    /**
     * 渲染图片列表
     */
    function renderImageList(images) {
        var imageListContainer = $('#imageList');
        imageListContainer.empty();
        
        if (!images || images.length === 0) {
            imageListContainer.append('<div class="no-images">暂无图片</div>');
            return;
        }
        
        images.forEach(function(image) {
            var imageItem = $('<div class="image-item"></div>');
            
            // 图片描述
            if (image.description) {
                imageItem.append('<div class="image-description">' + image.description + '</div>');
            }
            
            // 图片预览
            var imgPreview = $('<img class="image-preview" src="' + image.image_url + '" alt="' + (image.description || '图片') + '">');
            imgPreview.on('click', function() {
                // 打开大图预览
                layer.photos({
                    photos: {
                        data: [{
                            src: image.image_url,
                            alt: image.description || '图片'
                        }]
                    },
                    anim: 5
                });
            });
            imageItem.append(imgPreview);
            
            // 图片操作按钮
            var actionsDiv = $('<div class="image-actions"></div>');
            
            // 更新按钮
            var updateBtn = $('<div class="image-action-btn">更新</div>');
            updateBtn.on('click', function(e) {
                e.stopPropagation(); // 阻止冒泡，避免触发图片预览
                showUpdateImageModal(image.iid, image.description);
            });
            
            // 删除按钮
            var deleteBtn = $('<div class="image-action-btn">删除</div>');
            deleteBtn.on('click', function(e) {
                e.stopPropagation(); // 阻止冒泡，避免触发图片预览
                deleteImageConfirm(image.iid);
            });
            
            actionsDiv.append(updateBtn);
            actionsDiv.append(deleteBtn);
            imageItem.append(actionsDiv);
            
            imageListContainer.append(imageItem);
        });
    }
    
    /**
     * 上传图片
     */
    function uploadImage() {
        var fileInput = document.getElementById('imageFile');
        var descriptionInput = document.getElementById('imageDescription');
        var aid = document.getElementById('uploadAid').value;
        
        if (!fileInput.files || fileInput.files.length === 0) {
            layer.msg('请选择图片文件', {icon: 2});
            return;
        }
        
        var file = fileInput.files[0];
        var description = descriptionInput.value;
        
        // 从全局window.user_info对象中获取当前用户的ID
        var currentUserId = window.user_info && window.user_info.uid ? window.user_info.uid : 'e0873ff1-ba5f-496c-95a7-40c8c8e7faca';
        
        // 创建FormData对象
        var formData = new FormData();
        formData.append('aid', aid);
        formData.append('uid', currentUserId);
        formData.append('description', description);
        formData.append('image', file);
        
        // 显示上传中提示
        var loadingIndex = layer.load(2, {time: 10000});
        
        axios.post('/api/image/create/', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(function(res) {
            layer.close(loadingIndex);
            
            if (res.data.code === 0) {
                    layer.msg('图片上传成功', {icon: 1});
                    // 只关闭上传弹窗，不关闭图片详情模态框
                    if (uploadModalIndex) {
                        layer.close(uploadModalIndex);
                        uploadModalIndex = null;
                    }
                    // 重新加载图片列表
                    loadAccountImages(aid);
                } else {
                    layer.msg('上传失败：' + (res.data.message || '未知错误'), {icon: 2});
                }
        })
        .catch(function(error) {
            layer.close(loadingIndex);
            layer.msg('上传失败：网络错误', {icon: 2});
            console.error('图片上传失败:', error);
        });
    }
    
    /**
     * 更新图片描述
     */
    function updateImageDescription() {
        var iid = document.getElementById('updateIid').value;
        var description = document.getElementById('updateImageDescription').value;
        
        // 从全局window.user_info对象中获取当前用户的ID
        var currentUserId = window.user_info && window.user_info.uid ? window.user_info.uid : 'e0873ff1-ba5f-496c-95a7-40c8c8e7faca';
        
        // 创建FormData对象
        var formData = new FormData();
        formData.append('uid', currentUserId);
        formData.append('description', description);
        
        // 显示更新中提示
        var loadingIndex = layer.load(2, {time: 10000});
        
        axios.post('/api/image/update/' + iid + '/', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(function(res) {
            layer.close(loadingIndex);
            
            if (res.data.code === 0) {
                    layer.msg('更新成功', {icon: 1});
                    // 只关闭更新弹窗，不关闭图片详情模态框
                    if (updateModalIndex) {
                        layer.close(updateModalIndex);
                        updateModalIndex = null;
                    }
                    // 重新加载图片列表
                    loadAccountImages(currentAid);
                } else {
                    layer.msg('更新失败：' + (res.data.message || '未知错误'), {icon: 2});
                }
        })
        .catch(function(error) {
            layer.close(loadingIndex);
            layer.msg('更新失败：网络错误', {icon: 2});
            console.error('图片描述更新失败:', error);
        });
    }
    
    /**
     * 删除图片确认
     */
    function deleteImageConfirm(iid) {
        layer.confirm('确定要删除这张图片吗？', {
            btn: ['确定', '取消']
        }, function() {
            // 从全局window.user_info对象中获取当前用户的ID
            var currentUserId = window.user_info && window.user_info.uid ? window.user_info.uid : 'e0873ff1-ba5f-496c-95a7-40c8c8e7faca';
            
            // 创建FormData对象
            var formData = new FormData();
            formData.append('uid', currentUserId);
            
            // 显示删除中提示
            var loadingIndex = layer.load(2, {time: 10000});
            
            axios.post('/api/image/delete/' + iid + '/', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(function(res) {
                layer.close(loadingIndex);
                
                if (res.data.code === 0) {
                    layer.msg('删除成功', {icon: 1});
                    // 重新加载图片列表
                    loadAccountImages(currentAid);
                } else {
                    layer.msg('删除失败：' + (res.data.message || '未知错误'), {icon: 2});
                }
            })
            .catch(function(error) {
                layer.close(loadingIndex);
                layer.msg('删除失败：网络错误', {icon: 2});
                console.error('图片删除失败:', error);
            });
            
            layer.closeAll('dialog');
        });
    }
    
    /**
     * 清空待上传图片队列
     */
    window.clearPendingImages = function() {
        window.pendingImages = [];
    };
    
    /**
     * 添加记账带图片功能
     */
    window.addAccountWithImages = function(uid, amount, category, description, a_type, images) {
        // 先添加记账记录
        axios.post('/api/account/create/', {
            uid: uid,
            amount: amount,
            category: category,
            description: description,
            a_type: a_type
        })
        .then(function(res) {
            if (res.data.code === 0 && res.data.data && res.data.data.aid) {
                // 记账记录添加成功，获取aid
                var aid = res.data.data.aid;
                
                // 上传所有图片
                uploadAllPendingImages(aid, images)
                .then(function() {
                    layer.msg('记账记录添加成功并上传所有图片', {icon: 1});
                    // 重新加载记账记录列表
                    if (window.loadAccountList) {
                        window.loadAccountList();
                    }
                })
                .catch(function() {
                    layer.msg('记账记录添加成功，但部分图片上传失败', {icon: 2});
                    // 重新加载记账记录列表
                    if (window.loadAccountList) {
                        window.loadAccountList();
                    }
                });
            } else {
                layer.msg('添加记账记录失败：' + (res.data.message || '未知错误'), {icon: 2});
            }
        })
        .catch(function() {
            layer.msg('网络错误，无法添加记账记录', {icon: 2});
        });
    };
    
    /**
     * 批量上传所有待上传图片
     */
    function uploadAllPendingImages(aid, images) {
        return Promise.all(images.map(function(image) {
            return new Promise(function(resolve, reject) {
                // 从全局window.user_info对象中获取当前用户的ID
                var currentUserId = window.user_info && window.user_info.uid ? window.user_info.uid : 'e0873ff1-ba5f-496c-95a7-40c8c8e7faca';
                
                // 创建FormData对象
                var formData = new FormData();
                formData.append('aid', aid);
                formData.append('uid', currentUserId);
                formData.append('description', image.description || '');
                formData.append('image', image.file);
                
                axios.post('/api/image/create/', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(function(res) {
                    if (res.data.code === 0) {
                        resolve();
                    } else {
                        reject(new Error(res.data.message || '图片上传失败'));
                    }
                })
                .catch(reject);
            });
        }));
    }
});